package cn.com.tuns.assess.qsb.frame.widget;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.*;
import cn.com.tuns.assess.qsb.R;


public class DialogUtil extends Dialog {

	public enum Type{
		Top,
		Center,
		Bottom,
	}

	private Activity activity;

	private View root;

	private Type type;

	private boolean cancelable;

	/**
	 * 
	 * @param activity
	 * @param root
	 * @param type
	 *            0下方 1居中
	 */
	public DialogUtil(Activity activity, View root, Type type,
					  boolean cancelable) {
		super(activity, R.style.MyDialogTheme);
		this.activity = activity;
		this.root = root;
		this.type = type;
		this.cancelable = cancelable;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setCancelable(cancelable);
		setCanceledOnTouchOutside(cancelable);
		setContentView(root);

		if (type == Type.Top)
			setViewLocationTop();
		else if (type == Type.Bottom)
			setViewLocation();
		else
			setViewLocationCenter();
	}

	/**
	 * 设置dialog位于屏幕底部
	 */
	private void setViewLocationTop() {
		Window window = this.getWindow();
		window.setGravity(Gravity.TOP);

		WindowManager.LayoutParams lp = window.getAttributes();
		lp.x = 0;
		lp.y = 0;
		lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
		lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
		// 设置显示位置
		onWindowAttributesChanged(lp);
	}

	/**
	 * 设置dialog位于屏幕底部
	 */
	private void setViewLocation() {
		DisplayMetrics dm = activity.getResources().getDisplayMetrics();
		int height = dm.heightPixels;

		Window window = this.getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		lp.x = 0;
		lp.y = height;
		lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
		lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
		// 设置显示位置
		onWindowAttributesChanged(lp);
	}

	/**
	 * 设置dialog位于屏幕底部
	 */
	private void setViewLocationCenter() {
		DisplayMetrics dm = new DisplayMetrics();
		activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		int width = dm.widthPixels;

		Window window = this.getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		window.setGravity(Gravity.CENTER);
		lp.x = 0;
		lp.y = 0;
		lp.width = (int) (width * 0.8f);
		lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
		// 设置显示位置
		onWindowAttributesChanged(lp);
	}

//	public void show(int delay)
//	{
//		Handler handler=new Handler(Looper.getMainLooper());
//		handler.postDelayed(new Runnable() {
//			@Override
//			public void run() {
//				show();
//			}
//		},delay);
//	}
}
